<script>
import fetchHeaderVulnerabilityQuery from 'ee/security_dashboard/graphql/header_vulnerability.graphql';
import { convertToGraphQLId } from '~/graphql_shared/utils';
import { TYPENAME_VULNERABILITY } from '~/graphql_shared/constants';
import { fetchPolicies } from '~/lib/graphql';
import { s__ } from '~/locale';
import { createAlert } from '~/alert';
import { normalizeGraphQLVulnerability } from '../helpers';
import VulnerabilityFooter from './footer.vue';
import VulnerabilityHeader from './header.vue';
import VulnerabilityDetails from './vulnerability_details.vue';

export default {
  components: {
    VulnerabilityHeader,
    VulnerabilityDetails,
    VulnerabilityFooter,
  },
  props: {
    initialVulnerability: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      shouldSkipQuery: true,
      vulnerability: { ...this.initialVulnerability },
    };
  },
  apollo: {
    vulnerability: {
      manual: true,
      query: fetchHeaderVulnerabilityQuery,
      fetchPolicy: fetchPolicies.NO_CACHE,
      variables() {
        return {
          id: convertToGraphQLId(TYPENAME_VULNERABILITY, this.vulnerability.id),
        };
      },
      result({ data: { vulnerability } = {} }) {
        this.shouldSkipQuery = true;
        this.vulnerability = {
          ...this.vulnerability,
          ...normalizeGraphQLVulnerability(vulnerability),
        };
      },
      error() {
        createAlert({
          message: s__(
            'VulnerabilityManagement|Something went wrong while trying to refresh the vulnerability. Please try again later.',
          ),
        });
      },
      skip() {
        return this.shouldSkipQuery;
      },
    },
  },
  methods: {
    refetchVulnerability() {
      this.shouldSkipQuery = false;
      this.$apollo.queries.vulnerability.refetch();
    },
    updateVulnerability(newVulnerability) {
      this.vulnerability = newVulnerability;
    },
  },
};
</script>

<template>
  <div>
    <vulnerability-header
      ref="header"
      :vulnerability="vulnerability"
      @vulnerability-state-change="updateVulnerability"
    />
    <vulnerability-details :vulnerability="vulnerability" class="gl-pt-5" />
    <vulnerability-footer
      ref="footer"
      :vulnerability="vulnerability"
      @vulnerability-state-change="refetchVulnerability"
    />
  </div>
</template>
